package Chapter06;

/**
 * 暂停线程
 * Created by a on 2017/6/12.
 */
public class Test138 {

    public static void main(String[] args) {
        Sender sender = new Sender();
        Receiver receiver = new Receiver(sender);
        Thread t1 = new Thread(sender);
        Thread t2 = new Thread(receiver);
        t1.start();
        t2.start();
    }

}

class Sender implements Runnable {

    private String[] products = {"java编程词典","java范例大全","视频学java编程","细说java","java开发实战宝典"};
    private String product;
    private boolean isValid;



    public boolean isIsValid(){
        return isValid;
    }

    public void setIsValid(boolean isValid) {
        this.isValid = isValid;
    }

    public String getProduct(){
        return product;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++){
            while (isValid){
                Thread.yield();
            }
            product = products[i];
            System.out.println("发送:"+product);
            try {
                Thread.sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            isValid = true;
        }
    }
}

class Receiver implements Runnable {

    private Sender sender;

    public Receiver(Sender sender){
        this.sender = sender;
    }

    @Override
    public void run() {
        for (int i = 0 ; i<5 ;i++){
            while (!sender.isIsValid()){
                Thread.yield();
            }
            System.out.println("收到:"+sender.getProduct());
        }
        try {
            Thread.sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        sender.setIsValid(false);
    }
}


